﻿using System;

using System.Collections.Generic;
using System.Text;
using Silvermoon.Controls.Classes;
using Silvermoon.Shapes;
using System.Drawing;

namespace Silvermoon.Controls.Forms
{
    /// <summary>
    /// Tooltip that contains a Bubble control.
    /// </summary>
    public class ToolTip : ToolTipBase
    {
        #region fields

        private Bubble bubble;

        #endregion
        #region ctors/dtors

        public ToolTip()
            : base()
        {
            bubble = new Bubble();
            bubble.SizeChanged += OnBubbleSizeChanged;
            bubble.Margin = Margin.Zero;
            VisibleControls.AddFirst(bubble);
            Size = bubble.Size;
        }

        #endregion
        #region props

        public BubbleButtonCollection Items { get { return bubble.Buttons; } }

        #endregion
        #region methods

        private void OnBubbleSizeChanged(object sender, EventArgs e)
        {            
            Size = bubble.Size;
        }

        /// <summary>
        /// Calculates the location of the tooltip based on AnchorControl and AnchorPoint.
        /// </summary>
        public override void CalculatePosition()
        {
            if (AnchorControl == null) return;
            Rectangle anchorBounds = AnchorBounds;
            Point location = AnchorControl.PointToScreen(anchorBounds.Location);
            location.X += anchorBounds.Width / 2;
            int w2 = Width / 2;
            int offset = w2;
            int top = location.Y - Height;
            Placement placement = Placement.Bottom;
            if (top < 0)
            {
                top = location.Y + anchorBounds.Height;
                placement = Placement.Top;
            }

            int left = location.X - offset;

            if (left < 0)
            {
                offset += left;
                left = 0;
            }
            else if ((left + Width) > Screen.Width)
            {
                int d = left + Width - Screen.Width;
                offset += d;
                left -= d;
            }

            if (top < 0) top = 0;
            else if ((top + Height) > Screen.Height) top = Screen.Height - Height;

            this.Location = new Point(left, top);
            bubble.ArrowPlacement = placement;
            bubble.ArrowOffset = offset - w2;
        }

        protected override void OnLayout()
        {
            bubble.Size = Size;
            base.OnLayout();
        }


        #endregion
    }
}
